import { login, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    roles:[],
    menus:[],
    userId:'',
    email:''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_EMAIL: (state, email) => {
    state.email = email
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLE: (state, roles) => {
    state.roles = roles
  },
  SET_MENUS:(state, menus) => {
    state.menus = menus},
  SET_Id:(state, userId) => {
      state.userId = userId}

}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password} = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        console.log('----->',response)
        const { data } = response
        commit('SET_TOKEN', data.token) //存储到vuex中
        setToken(data.token)// 存储到cookies中
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        console.log(response)
        const { data } = response

        if (!data) {
          return reject('验证失败，请重新登录')
        }

        const { username, avatar,roleNames,userId,email} = data.user
        const { menus }=data
        commit('SET_NAME', username)
        commit('SET_AVATAR', avatar)
        commit('SET_ROLE',roleNames)
        commit('SET_MENUS',menus)
        commit('SET_Id',userId)
        commit('SET_EMAIL',email)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 退出登录
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
        removeToken() // 清空token
        resetRouter() 
        commit('RESET_STATE') //清空vuex
        resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

